package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {
    private ViewPager2 vpBanner;
    private RecyclerView rvCategory;
    private RecyclerView rvCourse;

    private BannerAdapter mBannerAdapter;
    private CategoryAdapter mCategoryAdapter;
    private CourseAdapter mCourseAdapter;

    private List<Banner> mBannerList = new ArrayList<>();
    private List<Category> mCategoryList = new ArrayList<>();
    private List<Course> mCourseList = new ArrayList<>();

    // 自动轮播相关
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private Runnable mBannerRunnable;
    private int currentPage = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        initData();
        initListener();
        return view;
    }

    private void initView(View view) {
        vpBanner = view.findViewById(R.id.vp_banner);
        rvCategory = view.findViewById(R.id.rv_category);
        rvCourse = view.findViewById(R.id.rv_course);

        // 初始化适配器
        mBannerAdapter = new BannerAdapter(getContext(), mBannerList);
        vpBanner.setAdapter(mBannerAdapter);

        mCategoryAdapter = new CategoryAdapter(getContext(), mCategoryList);
        rvCategory.setAdapter(mCategoryAdapter);

        mCourseAdapter = new CourseAdapter(getContext(), mCourseList);
        rvCourse.setAdapter(mCourseAdapter);

        // 类别图标：网格布局（2 列）
        rvCategory.setLayoutManager(new GridLayoutManager(getContext(), 2));
        // 推荐课程：网格布局（2 列）
        rvCourse.setLayoutManager(new GridLayoutManager(getContext(), 2));
    }

    private void initData() {
        // 获取轮播图数据
        RetrofitClient.getApiService().getBanners().enqueue(new Callback<List<Banner>>() {
            @Override
            public void onResponse(Call<List<Banner>> call, Response<List<Banner>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    mBannerList.clear();
                    mBannerList.addAll(response.body());
                    mBannerAdapter.notifyDataSetChanged();
                    startBannerAutoPlay();
                }
            }

            @Override
            public void onFailure(Call<List<Banner>> call, Throwable t) {
                showError("轮播图数据加载失败");
            }
        });

        // 获取分类数据
        RetrofitClient.getApiService().getCategories().enqueue(new Callback<List<Category>>() {
            @Override
            public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    mCategoryList.clear();
                    mCategoryList.addAll(response.body());
                    mCategoryAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<List<Category>> call, Throwable t) {
                showError("分类数据加载失败");
            }
        });

        // 获取推荐课程数据
        RetrofitClient.getApiService().getRecommendCourses().enqueue(new Callback<List<Course>>() {
            @Override
            public void onResponse(Call<List<Course>> call, Response<List<Course>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    mCourseList.clear();
                    mCourseList.addAll(response.body());
                    mCourseAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<List<Course>> call, Throwable t) {
                showError("推荐课程数据加载失败");
            }
        });
    }

    private void initListener() {
        // 轮播图点击跳转课程详情
        mBannerAdapter.setOnBannerClickListener(courseId -> {
            Intent intent = new Intent(getContext(), CourseDetailActivity.class);
            intent.putExtra("courseId", courseId);
            startActivity(intent);
        });

        // 类别图标点击跳转课程列表
        mCategoryAdapter.setOnCategoryClickListener(categoryId -> {
            Intent intent = new Intent(getContext(), CategoryListActivity.class);
            intent.putExtra("categoryId", categoryId);
            startActivity(intent);
        });

        // 推荐课程点击跳转课程详情
        mCourseAdapter.setOnCourseClickListener(courseId -> {
            Intent intent = new Intent(getContext(), CourseDetailActivity.class);
            intent.putExtra("courseId", courseId);
            startActivity(intent);
        });
    }

    // 启动轮播图自动播放（3 秒切换一次）
    private void startBannerAutoPlay() {
        if (mBannerList.isEmpty()) return;

        mBannerRunnable = () -> {
            currentPage = (currentPage + 1) % mBannerList.size();
            vpBanner.setCurrentItem(currentPage);
            mHandler.postDelayed(mBannerRunnable, 3000);
        };
        mHandler.postDelayed(mBannerRunnable, 3000);
    }

    private void showError(String message) {
        if (getContext() != null) {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 停止轮播，避免内存泄漏
        mHandler.removeCallbacks(mBannerRunnable);
    }
}